#include "inc/dev_nvs.h"
#include "E:\app\Espressif\frameworks\esp-idf-v5.0.1\components\nvs_flash\include\nvs_flash.h"

void nvs_init(void)
{
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);  
}

esp_err_t nvs_save_str(char* key, char* value)
{
    nvs_handle my_handle;
    if(nvs_open("nvs", NVS_READWRITE, &my_handle) == ESP_OK)
    {
        nvs_set_str(my_handle, key, value);
        nvs_commit(my_handle);
        //ESP_LOGI("nvs_write"," %s write succuss!", value);
        return ESP_OK;
    }
    else{
        //ESP_LOGE("nvs","Can not open");
        return ESP_FAIL;
    }
}

esp_err_t nvs_read_str(char* key,char* outvalue)
{
    nvs_handle my_handle;
    if(nvs_open("nvs", NVS_READONLY, &my_handle) == ESP_OK)
    {
        size_t required_size;
        nvs_get_str(my_handle, key, NULL, &required_size);
        outvalue = (char*)malloc(required_size);
        nvs_get_str(my_handle, key, outvalue, &required_size);
        //ESP_LOGI("nvs_read","read succuss!");
        return ESP_OK;
    }
    else{
        //ESP_LOGE("nvs","Can not open");
        return ESP_FAIL;
    }
}
